package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.PostLike;
import com.ruoyi.system.domain.PostReward;
import com.ruoyi.system.dto.PostLikeDTO;
import com.ruoyi.system.dto.PostRewardDTO;
import com.ruoyi.system.mapper.PostLikeMapper;
import com.ruoyi.system.mapper.PostRewardMapper;
import com.ruoyi.system.service.PostsInteractionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 动态互动（点赞/打赏）业务实现
 */
@Service
public class PostsInteractionServiceImpl implements PostsInteractionService {
    @Autowired
    private PostLikeMapper likeMapper;
    @Autowired
    private PostRewardMapper rewardMapper;

    /** 点赞列表 */
    @Override
    public List<PostLikeDTO> selectLikes(PostLike like) {
        return likeMapper.selectList(like).stream().map(this::toLikeDto).collect(Collectors.toList());
    }

    /** 打赏列表 */
    @Override
    public List<PostRewardDTO> selectRewards(PostReward reward) {
        return rewardMapper.selectList(reward).stream().map(this::toRewardDto).collect(Collectors.toList());
    }

    /** 打赏总金额 */
    @Override
    public BigDecimal sumRewardAmount(Long postId) {
        List<PostRewardDTO> list = selectRewards(buildReward(postId));
        return list.stream().map(PostRewardDTO::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    private PostReward buildReward(Long postId) {
        PostReward r = new PostReward();
        r.setPostId(postId);
        return r;
    }

    private PostLikeDTO toLikeDto(PostLike l) {
        PostLikeDTO dto = new PostLikeDTO();
        dto.setId(l.getId());
        dto.setUserId(l.getUserId());
        dto.setUserName(l.getUserName());
        dto.setAvatar(l.getAvatar());
        dto.setCreateTime(l.getCreatedAt());
        return dto;
    }

    private PostRewardDTO toRewardDto(PostReward r) {
        PostRewardDTO dto = new PostRewardDTO();
        dto.setId(r.getId());
        dto.setUserId(r.getUserId());
        dto.setUserName(r.getUserName());
        dto.setAvatar(r.getAvatar());
        dto.setUserAvatar(r.getAvatar());
        dto.setAmount(r.getAmount());
        dto.setMessage(r.getMessage());
        dto.setCreateTime(r.getCreatedAt());
        return dto;
    }
}
